import pymysql
import requests
import json
import logging

import os
import sys

def resource_path(relative_path):
    """获取打包后资源的绝对路径"""
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 常量定义
COMMON_ZERO = "0"
COMMON_ONE = "1"
COMMON_TWO = "2"
MES_SYNC_LOC_STATUS_URL = "/load_and_unload_material/sync/connection_position"

# 数据库配置
db_config = {
    "host": "192.168.100.253",
    "user": "root",
    "password": "J9BleIPrlAE8lQG1u",
    "database": "ry_tms_v2"
}

# 获取配置项
def get_config_value(cursor, key):
    cursor.execute("SELECT param_value FROM tms_config WHERE param_key = %s", (key,))
    row = cursor.fetchone()
    return row['param_value'] if row else None

# 构造同步参数并发送给 MES
def sync_to_mes(tms_storage_location, mes_url):
    # 检查URL格式，如果没有协议头则添加http://
    if not mes_url.startswith(('http://', 'https://')):
        mes_url = 'http://' + mes_url
        logging.warning("自动为MES_URL添加协议头: %s", mes_url)

    storage_status = tms_storage_location['storage_location_status']
    status = tms_storage_location['status']

    state = ""
    if storage_status == COMMON_ZERO:
        state = "occupy"
    elif storage_status == COMMON_ONE:
        state = "free"
    elif storage_status == COMMON_TWO:
        state = "pre_occupy"

    sync_mes = {
        "sync_type": "add",
        "code": tms_storage_location['business_id'],
        "name": tms_storage_location['storage_location_name'],
        "state": state,
        "connection_position_active": COMMON_ONE if status == COMMON_ONE else COMMON_ZERO
    }

    url = mes_url + MES_SYNC_LOC_STATUS_URL
    headers = {"Content-Type": "application/json"}
    response = requests.post(url, data=json.dumps(sync_mes), headers=headers)

    logging.info("接驳位 %s 状态变更为 %s, 通知MES结果: [%s]",
                 sync_mes["code"], sync_mes["state"], response.text)
    return response.text

def main():
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            mes_switch = get_config_value(cursor, "MES_SWITCH")
            if mes_switch != COMMON_TWO:
                logging.info("MES_SWITCH 配置为 %s，无需同步 MES", mes_switch)
                return

            mes_url = get_config_value(cursor, "MES_URL")
            if not mes_url:
                logging.error("未配置 MES_URL")
                return

            # 查询所有储位
            cursor.execute("SELECT * FROM tms_storage_location WHERE id in (1808090701852884993,1808090706336595970,1808090708450525185,1808090710337961986,1808090712669995010,1808090714620346370,1808090717065625601,1808090719280218114,1808090721570308098,1808090723755540481)")
            all_rows = cursor.fetchall()
            total = len(all_rows)
            logging.info("共查询到 %d 条储位信息。", total)

            # 🔴 新增：启动前提示用户是否继续
            user_input = input("按 Enter 开始同步，输入 q 后回车退出: ").strip().lower()
            if user_input == 'q':
                logging.info("用户取消执行，程序退出。")
                return

            # 分批处理
            batch_size = 10
            for start in range(0, total, batch_size):
                end = min(start + batch_size, total)
                batch = all_rows[start:end]
                logging.info("正在处理第 %d 到 %d 条储位数据...", start + 1, end)

                for row in batch:
                    sync_to_mes(row, mes_url)

                # 🔴 每批等待确认
                user_input = input("按 Enter 继续下一批，输入 q 后回车退出: ").strip().lower()
                if user_input == 'q':
                    logging.info("用户中止操作，已退出程序。")
                    break

    finally:
        connection.close()

if __name__ == "__main__":
    main()